# document processing infrastructure
from docproc import Processor, Document
from docproc import ProcessorStatus

# local modules
import sys
import re

class RegexExtractor(Processor.Processor):

	def __init__(self, name):
		Processor.Processor.__init__(self, name)

	def ConfigurationChanged(self, attributes):
		log(log.FLOG_STATUS, '%s: ConfigurationChanged: Parameters given: %s' % (self.GetName(), str(attributes)))

		self._regex = self.GetParameter('Regex') # defaults to ""
		self._input = self.GetParameter('Input')           # defaults to ""
		self._output = self.GetParameter('Output')         # defaults to ""  
		self._default = self.GetParameter('Default')         # defaults to ""       

	def Process(self, uri, document):
		log(log.FLOG_DEBUG, '%s: Process: working on document: %s' % (self.GetName(), uri))
		if (self._regex and (not self._regex.isspace())):
			if (self._input and (not self._input.isspace())):
				if (self._output and (not self._output.isspace())):
					inputvalue = document.GetValue(self._input, "")
					if inputvalue != '':
						#m = re.match(r"http://[a-zA-Z0-9\.]*/([a-zA-Z]+)/[A-Za-z0-9\.\/\?=&;%]*", "http://www.atlascopco.com/benl/products/rental/")
						m = re.match(self._regex, inputvalue)
						if (m != None): # and document.Has(self._output)
							value = m.group(1)
							log(log.FLOG_DEBUG, value)
							document.Set(self._output, value)
						else:
							if (self._default and (not self._default.isspace())):
								document.Set(self._output, self._default)
							log(log.FLOG_STATUS, '%s: No match found for regular expression in : %s' % (self.GetName(), self._regex))
					else:
						log(log.FLOG_DEBUG, 'No inputvalue found' )
				else:
					log(log.FLOG_DEBUG, 'No _output defined' )
			else:
				log(log.FLOG_DEBUG, 'No _input defined' )
		else:
			log(log.FLOG_DEBUG, 'No _regex defined' )
		return ProcessorStatus.OK